package com.example.everying.framework.websocket.utils;

import com.example.everying.model.entity.system.SysNotification;
import com.example.everying.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class WebSocketRedisUtil {
    private static RedisUtils redisUtils;

    @Autowired
    private void setService(RedisUtils redisUtils) {
        WebSocketRedisUtil.redisUtils = redisUtils;
    }

    // Redis Key 常量
    private static final String WS_ACTIVE_KEY = "ws:active_sessions";

    /**
     * 更新用户活跃时间
     */
    public void updateUserActivity(String userId) {
        // 写入最新时间戳并设置Key过期时间（10秒）
        try {
            long timestamp =  System.currentTimeMillis() / 1000;
//            log.info("用户:{} 活跃状态更新时间戳:{}", userId, timestamp);
            redisUtils.setCacheMapValue(WS_ACTIVE_KEY, userId, timestamp);
//            redisUtils.expire(WS_ACTIVE_KEY, 60, TimeUnit.SECONDS);
            // 记录成功日志
//            log.info("用户:{} 活跃状态更新成功", userId);
        } catch (Exception e) {
            // 记录异常信息便于排查
            log.error("更新用户:{} 活跃状态失败", userId, e);
        }
    }

    /**
     * 获取所有活跃会话
     */
    public Map<String, Long> getActiveSessions() {
        Map<String, Object> rawMap = redisUtils.getCacheMap(WS_ACTIVE_KEY);
        Map<String, Long> result = new HashMap<>();

        rawMap.forEach((userId, timestamp) -> {
            if (timestamp instanceof Long) {
                result.put(userId, ((Long) timestamp));
            } else if (timestamp instanceof Integer) {
                result.put(userId, ((Integer) timestamp).longValue());
            } else if (timestamp instanceof String) {
                try {
                    long value = Long.parseLong((String) timestamp);
                    result.put(userId, value);
                } catch (NumberFormatException e) {
                    log.warn("无法解析用户 {} 的时间戳: {}", userId, timestamp);
                }
            }
        });
        return result;
    }

    /**
     * 清理指定用户记录
     */
    public void cleanUserRecord(String userId) {
        log.info("清理用户 {} 的记录", userId);
        if (userId != null) {
            redisUtils.deleteCacheMapValue(WS_ACTIVE_KEY, userId);
        }
    }

    /**
     * 存储离线消息到Redis
     */
    public void saveOfflineNotification(String userId, SysNotification notification) {
        String offlineKey = "offline_messages:" + userId;
        try {
            // 将通知添加到Redis列表
            redisUtils.leftPush(offlineKey, notification);
            // 设置过期时间，7天
            redisUtils.expire(offlineKey, 7 * 24 * 60 * 60);
        } catch (Exception e) {
            log.error("存储用户{}离线消息失败: {}", userId, e.getMessage());
        }
    }

}
